package controller;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.pagehelper.PageInfo;

import domain.Message;
import domain.Movie;
import domain.Music;
import service.IMovieService;

@Controller
public class MovieController {
	@Autowired
	private IMovieService service;
	
	@RequestMapping("/movie")
	public String goMovie(HttpServletRequest req, Integer page) {
		Integer size = 9;//默认为一页9条数据
		if (page == null) {
			page = 1; //若请求中没有分页的信息 就从第一页开始
		}
		List<Movie> all = service.listAll(page, size);
		PageInfo<Message> pageInfo = new PageInfo(all);
		//将pageInfo放到请求中做分页
		req.setAttribute("pageInfo", pageInfo);
		req.setAttribute("movie", all);
		return "front/movie";
	}

	@RequestMapping("/sharemovie")
	public String goMsg(HttpServletRequest req, Integer page) {
		Integer pageSize = 7;
		if (page == null) {
			page = 1; //默认第一页开始
		}
		List<Movie> all = service.listAll(page, pageSize);
		PageInfo<Message> pageInfo = new PageInfo(all);
		req.setAttribute("pageInfo", pageInfo);
		req.setAttribute("movie", all);
		//防止表单重复提交
		String token = UUID.randomUUID().toString();
		req.setAttribute("tokenInForm", token);
		req.getSession().setAttribute("tokenInSession", token);
		return "admin/movie";
	}

	@RequestMapping("/movDelete")
	public void delete(HttpServletRequest req, HttpServletResponse resp, Long id) throws Exception {
		Integer state = service.deleteMovie(id);
		if (state > 0) {
			req.setAttribute("isSuccess", "删除成功");
		} else {
			req.setAttribute("isSuccess", "删除失败");
		}
		req.getRequestDispatcher("/sharemovie").forward(req, resp);
	}

	@RequestMapping("/addMovie")
	public void addMovie(HttpServletRequest req, HttpServletResponse resp, String name, String path, String tokenInForm)
			throws Exception {
		//这边执行收会转发到上面 所以session肯定不为空 可以toString
		String tokenInSession = (String) req.getSession().getAttribute("tokenInSession");
		if (tokenInForm.equals(tokenInSession)) {
			Movie movie = new Movie();
			movie.setName(name);
			movie.setPath(path);
			Integer state = service.addMovie(movie);
			if (state > 0) {
				req.setAttribute("isSuccess", "添加成功");
			} else {
				req.setAttribute("isSuccess", "添加失败");
			}
			req.getSession().removeAttribute("tokenInSession");
		}
		req.getRequestDispatcher("/sharemovie").forward(req, resp);
	}
}
